<?php


namespace app\common\model;


use think\Exception;

class TaskRelease extends TimeModel
{

    protected $name = "task_release";

    protected $deleteTime = false;

    const TABLE_NAME = 'task_release';

    // 发布状态
    const STATUS_PUBLISH_NO = 0;
    const STATUS_PUBLISH_YES = 1;

    // 领取状态
    const RECEIVE_STATUS_NO = 0;
    const RECEIVE_STATUS_UNFINISHED = 1;
    const RECEIVE_STATUS_FINISHED = 2;
    public static $receiveStatusMap = array(
        self::RECEIVE_STATUS_NO => '未领取',
        self::RECEIVE_STATUS_UNFINISHED => '未领完',
        self::RECEIVE_STATUS_FINISHED => '已领完'
    );

    // 删除状态
    const DELETE_NO = 0;
    const DELETE_YES = 1;

    // 是否可领取多次
    const CLAIM_MANY_NO = 0;
    const CLAIM_MANY_YES = 1;
    public static $claimManyMap = array(
        self::CLAIM_MANY_NO => '否',
        self::CLAIM_MANY_YES => '是'
    );

    // 发布来源
    const RELEASE_SOURCE_BACKEND = 1;
    const RELEASE_SOURCE_FRONT = 2;
    const RELEASE_SOURCE_OTHER = 3;
    public static $releaseSourceMap = array(
        self::RELEASE_SOURCE_BACKEND => '后台',
        self::RELEASE_SOURCE_FRONT => '前端',
        self::RELEASE_SOURCE_OTHER => '其他'
    );


    /**
     * 获取 发布任务列表信息
     *
     * @param array $conditions
     * @param int $page
     * @param int $page_size
     * @param string $order
     * @return mixed
     * @throws Exception
     */
    public function getListInfo($conditions=[], $page=1, $page_size=10, $order='a.id')
    {

        $new_conditions = $conditions;
        $new_conditions[] = array('a.is_del', '=', self::DELETE_NO);
        try {
            $join = [
                ['ea_system_admin admin', 'a.release_uid=admin.id', 'left'],
                ['ea_dim_area area', 'a.community=area.id', 'left'],
                ['ea_dim_category cate', 'a.cate_id=cate.id', 'left']
            ];
            $field = 'a.id, a.title, a.release_time, a.release_uid, a.release_source,
            a.area, a.township, a.community, a.status, a.max_count, a.cate_id, a.receive_count, a.view_count,
            admin.username as release_user_name, area.name as community_name, cate.title as category_title';
            return model(self::TABLE_NAME)->pageList($new_conditions, $field, $order, $page, $page_size, 'a', $join);
        }catch (\Exception $e){
            self::writeLog([
                'msg' => $e->getMessage(),
                'sql' => lastSql()
            ]);
            throw new Exception('查询失败');
        }
    }

    /**
     * 获取详情
     *
     * @param $conditions
     * @return mixed
     * @throws Exception
     */
    public function getDetail($conditions)
    {

        $new_conditions = $conditions;
        $new_conditions[] = array('a.is_del', '=', self::DELETE_NO);
        try{
            $join = [
                ['ea_system_admin admin', 'a.release_uid=admin.id', 'left'],
                ['ea_dim_area area', 'a.community=area.id', 'left'],
                ['ea_dim_category cate', 'a.cate_id=cate.id', 'left']
            ];
            $field = 'a.id, a.title, a.release_time, a.release_uid, a.release_source, a.content,
            a.area, a.township, a.community, a.status, a.max_count, a.cate_id, a.receive_count, a.view_count,
            admin.username as release_user_name, area.name as community_name, cate.title as category_title';
            return model(self::TABLE_NAME)->getInfo($new_conditions, $field, 'a', $join);
        }catch (\Exception $e){
            self::writeLog([
                'msg' => $e->getMessage(),
                'sql' => lastSql()
            ]);
            throw new Exception('查询失败');
        }
    }

    /**
     * 任务 领取
     *
     * @param $task_id
     * @param $user_id
     * @return int|string
     * @throws Exception
     */
    public function claim($task_id, $user_id)
    {

        // 任务 校验
        $conditions = [];
        $conditions[] = array('id', '=', $task_id);
        $task_info = model(self::TABLE_NAME)->getInfo($conditions);
        if(empty($task_info)){ throw new Exception('任务不存在'); }
        elseif($task_info['status'] != self::STATUS_PUBLISH_YES){  throw new Exception('当前任务已关闭'); }
        elseif($task_info['receive_status'] == self::RECEIVE_STATUS_FINISHED){ throw new Exception('任务已领完'); }

        // 同源任务 校验
        if(
            $task_info['release_source'] == self::RELEASE_SOURCE_FRONT &&
                $task_info['release_uid'] == $user_id
        ){ throw new Exception('同源任务，无法领取'); }

        // 领取限制 校验
        if($task_info['is_claim_many'] == self::CLAIM_MANY_NO){
            $task_user_conditions = array();
            $task_user_conditions[] = array('claim_uid', '=', $user_id);
            $task_user_conditions[] = array('task_id', '=', $task_id);
            $task_user_conditions[] = array('is_del', '=', self::DELETE_NO);
            $task_user_info = model(TaskUser::TABLE_NAME)->getInfo($task_user_conditions);
            if(!empty($task_user_info)){ throw new Exception('当前任务已领取，请勿重复领取'); }
        }

        try{
            model(self::TABLE_NAME)->startTrans();
            // 更新发布任务信息
            $update_data = $task_user_data = [];
            $task_receive_max = $task_info['max_count'];
            $task_receive_count = $task_info['receive_count'];
            if($task_receive_count >= $task_receive_max){throw new Exception('当前任务已领取完毕');}
            $task_receive_count += 1;
            $task_receive_status = $task_receive_max == $task_receive_count ? self::RECEIVE_STATUS_FINISHED
                : self::RECEIVE_STATUS_UNFINISHED;
            $update_data['receive_count'] = $task_receive_count;
            $update_data['receive_status'] = $task_receive_status;
            model(self::TABLE_NAME)->updateInfo($update_data, $conditions);

            // 添加用户领取任务记录
            $task_user_data['task_id'] = $task_id;
            $task_user_data['claim_uid'] = $user_id;
            $task_user_data['task_snapshot'] = json_encode($task_info, 256);
            $task_id = model(TaskUser::TABLE_NAME)->add($task_user_data);
            model(self::TABLE_NAME)->commit();
            return $task_id;
        }catch (\Exception $e){
            model(self::TABLE_NAME)->rollback();
            self::writeLog([
                'msg' => $e->getMessage(),
                'sql' => lastSql()
            ]);
            throw new Exception('添加失败');
        }
    }
}